﻿using System;
using System.Configuration;
using System.Collections.Generic;
using System.Web;
using System.Web.UI.WebControls;
using DynamicComparer;
using Shuba.Model;

namespace Shuba.Web.master
{
    public partial class cluster_plan_list : basePage
    {
        Int64 TargetAmount = 0, TargetNoa = 0, TargetAmountReal = 0, TargetNoaReal = 0;
        string msg = "";
        bool IsView, IsAdd, IsEdit, IsDelete, IsChecker;

        private void BindData()
        {
            Shuba.Business.ClusterTarget _ClusterTarget = new Shuba.Business.ClusterTarget();
            List<ClusterTargetInfo> list;

            string TargetYear = ddlYear.Text;
            string RegionalID = ddlRegion.SelectedValue.ToString();

            list = _ClusterTarget.GetList(RegionalID, TargetYear, Session["UnitID"].ToString());

            if (ViewState["SortEx"].ToString().Trim() != "")
            {
                string sort = sort = ViewState["SortEx"].ToString() + " " + ViewState["Sort"];
                DynamicComparer<ClusterTargetInfo> comparer = new DynamicComparer<ClusterTargetInfo>(sort);
                list.Sort(comparer);
            }

            gvList.DataSource = list;
            gvList.DataBind();

            lblAmountCluster.Text = TargetAmount.ToString("N0");
            lblNoaCluster.Text = TargetNoa.ToString("N0");
            lblAmountRealCluster.Text = TargetAmountReal.ToString("N0");
            lblNoaRealCluster.Text = TargetNoaReal.ToString("N0");

            Shuba.Business.RegionalTarget _RegionTarget = new Shuba.Business.RegionalTarget();
            Shuba.Model.RegionalTargetInfo bi;

            bi = _RegionTarget.Get(RegionalID, TargetYear);

            lblYear.Text = TargetYear;
            lblRegion.Text = ddlRegion.SelectedItem.Text;
            lblAmount.Text = bi.TargetAmount.ToString("N0");
            lblNoa.Text = bi.Noa.ToString("N0");

            lblAmountReal.Text = bi.TargetAmountReal.ToString("N0");
            lblNoaReal.Text = bi.NoaReal.ToString("N0");

            if (IsDelete) gvList.Columns[6].Visible = true; else gvList.Columns[6].Visible = false;
            
            //FOR APPROVAL GRID
            if (IsChecker)
            {
                BindApprovalData();

                if (ApprovalGrid.Rows.Count > 0) { ApprovalPnl.Visible = true; } else { ApprovalPnl.Visible = false; }
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            this.Form.DefaultButton = btnSearch.UniqueID;

            string acl = GetUserAccess("TARGET_CLUSTER");
            
            IsView = IsUserView(acl);
            IsAdd = IsUserAdd(acl);
            IsEdit = IsUserEdit(acl);
            IsDelete = IsUserDelete(acl);
            IsChecker = IsUserChecker(acl);

            if (!IsView)
            {
                msg = this.GetGlobalResourceObject("Messages", "NoPrivilege").ToString();
                AlertAndRedirect(msg, ResolveUrl(ConfigurationManager.AppSettings["default_url"]));
            }

            if (!IsPostBack)
            {
                InitYearList();
                InitRegionList();

                ddlYear.SelectedIndex = ddlYear.Items.IndexOf(ddlYear.Items.FindByValue(ProcessingDate().Year.ToString()));

                InitSort();
                BindData();

                LabelTitle.Text = GetPageTitle("TARGET_CLUSTER");

                if (IsAdd)
                {
                    btnAdd.Enabled = true;
                    btnUpload.Enabled = true;
                }
                else
                {
                    btnAdd.Enabled = false;
                    btnUpload.Enabled = false;
                }
            }
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            string Year = ddlYear.SelectedValue;
            string Region = ddlRegion.SelectedValue;

            string url = "cluster_plan_add.aspx" + "?yr=" + Year + "&reg=" + Region; 
            
            Response.Redirect(url);
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            BindData();
        }

        protected void InitYearList()
        {
            Int32 NextYear = Convert.ToInt32(ProcessingDate().Year.ToString()) + 4;
            Int32 LastYear = Convert.ToInt32(ProcessingDate().Year.ToString()) - 1;

            for (var n = LastYear; n < NextYear; n++)
            {
                ddlYear.Items.Add(n.ToString());
            }
        }

        protected void gvList_RowCommand(Object sender, GridViewCommandEventArgs e)
        {
            
            switch (e.CommandName)
            {
                //case "Edit":
                //    Response.Redirect("cluster_plan_edit.aspx?a=ed&id=" + e.CommandArgument + "&yr=" + lblYear.Text);
                //    break;
                case "Remove":
                    string id = e.CommandArgument.ToString();
                    Shuba.Business.ClusterTarget _ClusterTarget = new Shuba.Business.ClusterTarget();
                    if (!_ClusterTarget.IsDependency(id, lblYear.Text))
                    {
                        Shuba.Model.ClusterTargetInfo _bi = _ClusterTarget.Get(id, lblYear.Text);
                        _bi.UpdateBy = HttpContext.Current.User.Identity.Name;
                        _bi.UpdateDate = ProcessingDate();
                        _bi.ActType = "DELETE";
                        try
                        {
                            _ClusterTarget.Save(_bi);
                            AddLog("DELETE", "DELETE CLUSTER TARGET PLAN");
                        }
                        catch (Exception ex)
                        {
                            ErrBox.Visible = true;
                            ErrMsg.Text = ex.Message;
                        }
                        RestartPage();
                    }
                    else
                    {
                        Alert("Cant deleted, has already Unit Target Plan assigned");
                    }
                    break;
            }
        }

        protected void gvList_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvList.PageIndex = e.NewPageIndex;
            BindData();
        }

        protected void gvList_Sorting(object sender, GridViewSortEventArgs e)
        {
            SortDirection(e.SortExpression,e.SortDirection.ToString());
            ViewState["SortEx"] = e.SortExpression;
            gvList.PageIndex = 0;
            BindData();
        }

        protected void gvList_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            string Amount, Noa, AmountReal, NoaReal;

            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                //LinkButton btnEdit = (LinkButton)e.Row.FindControl("btnEdit");
                LinkButton btnDelete = (LinkButton)e.Row.FindControl("btnDelete");

                Amount = e.Row.Cells[2].Text.Replace(",", "").Trim();
                Noa = e.Row.Cells[3].Text.Replace(",", "").Trim();

                AmountReal = e.Row.Cells[4].Text.Replace(",", "").Trim();
                NoaReal = e.Row.Cells[5].Text.Replace(",", "").Trim();

                if (Amount != "0") TargetAmount += Convert.ToInt64(Amount); else TargetAmount += 0;
                if (Noa != "0") TargetNoa += Convert.ToInt64(Noa); else TargetNoa += 0;

                if (AmountReal != "0") TargetAmountReal += Convert.ToInt64(AmountReal); else TargetAmountReal += 0;
                if (NoaReal != "0") TargetNoaReal += Convert.ToInt64(NoaReal); else TargetNoaReal += 0;

                //if (Amount != "0" && Noa != "0")
                if (Amount != "0" || Noa != "0" || AmountReal !="0" || NoaReal != "0")
                {
                    //TargetAmount += Convert.ToInt64(Amount);
                    //TargetNoa += Convert.ToInt64(Noa);

                    if (IsDelete)
                    {
                        btnDelete.Enabled = true;
                    }
                    else
                    {
                        btnDelete.Enabled = false;
                        btnDelete.OnClientClick = "";
                    }
                }
                else
                {
                    btnDelete.Enabled = false;
                    btnDelete.OnClientClick = "";
                    //btnEdit.Enabled = false;
                }
            }
        }

        /*======================================
                APPROVAL GRID START HERE
         =======================================
         */
        private void BindApprovalData()
        {
            Shuba.Business.ClusterTarget _ClusterTarget = new Shuba.Business.ClusterTarget();
            List<ClusterTargetInfo> list;

            list = _ClusterTarget.GetListApproval(ddlYear.Text, HttpContext.Current.User.Identity.Name, Session["UnitID"].ToString());
            if (ViewState["SortEx"].ToString().Trim() != "")
            {
                string sort = sort = ViewState["SortEx"].ToString() + " " + ViewState["Sort"];
                DynamicComparer<ClusterTargetInfo> comparer = new DynamicComparer<ClusterTargetInfo>(sort);
                list.Sort(comparer);
            }
            ApprovalGrid.DataSource = list;
            ApprovalGrid.DataBind();
        }

        protected void ApprovalGrid_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            ApprovalGrid.PageIndex = e.NewPageIndex;
            BindApprovalData();
        }

        protected void ApprovalGrid_Sorting(object sender, GridViewSortEventArgs e)
        {
            SortDirection(e.SortExpression, e.SortDirection.ToString());
            ViewState["SortEx"] = e.SortExpression;
            ApprovalGrid.PageIndex = 0;
            BindApprovalData();
        }

        protected void btnApprove_Click(object sender, EventArgs e)
        {
            foreach (GridViewRow row in ApprovalGrid.Rows)
            {
                CheckBox chkItemSelect = (CheckBox)row.FindControl("chkItemSelect");
                string id = Convert.ToString(ApprovalGrid.DataKeys[row.RowIndex].Value.ToString());
                if (chkItemSelect.Checked)
                {
                    Approve(id, true);
                }
            }
            msg = this.GetGlobalResourceObject("Messages", "ApproveAlert").ToString();
            BindData();
            Alert(msg); 
            //AlertAndRedirect(msg, Request.Url.PathAndQuery);
        }

        protected void btnReject_Click(object sender, EventArgs e)
        {
            foreach (GridViewRow row in ApprovalGrid.Rows)
            {
                CheckBox chkItemSelect = (CheckBox)row.FindControl("chkItemSelect");
                string id = Convert.ToString(ApprovalGrid.DataKeys[row.RowIndex].Value.ToString());
                if (chkItemSelect.Checked)
                {
                    Approve(id, false);
                }
            }
            msg = this.GetGlobalResourceObject("Messages", "NoApprove").ToString();
            BindData();
            Alert(msg);
            //AlertAndRedirect(msg, Request.Url.PathAndQuery);
        }

        private int Approve(string id, bool IsApprove)
        {
            int result = 0;
            string ActType, TargetYear = ddlYear.Text;

            Shuba.Business.ClusterTarget _ClusterTarget = new Shuba.Business.ClusterTarget();
            Shuba.Model.ClusterTargetInfo bi = new Shuba.Model.ClusterTargetInfo();

            bi = _ClusterTarget.GetApprovalByID(id, TargetYear);
            ActType = bi.ActType;
            bi.UpdateBy = HttpContext.Current.User.Identity.Name;
            bi.UpdateDate = ProcessingDate();

            if (IsApprove)
            {
                result = _ClusterTarget.Approve(id, TargetYear, ActType);
                AddLog("APPROVAL", "APPROVE CLUSTER TARGET PLAN");
            }
            else
            {
                result = _ClusterTarget.Reject(id, TargetYear);
                AddLog("APPROVAL", "REJECT CLUSTER TARGET PLAN");
            }
            return result;
        }

        private void InitRegionList()
        {
            Shuba.Business.Regional _Region = new Shuba.Business.Regional();
            List<RegionalInfo> list;

            list = _Region.GetList("%", Session["UnitID"].ToString(), HttpContext.Current.User.Identity.Name, ConfigurationManager.AppSettings["app.code"]);
            ddlRegion.DataTextField = "RegionalName";
            ddlRegion.DataValueField = "RegionalID";
            ddlRegion.DataSource = list;

            ddlRegion.DataBind();

            if (ddlRegion.Items.Count == 0)
            {
                ListItem ListAll = new ListItem();
                ListAll.Value = "";
                ListAll.Text = "";
                ddlRegion.Items.Insert(0, ListAll);
            }
        }

        protected void btnApproveAll_Click(object sender, EventArgs e)
        {
            int ErrorCount = 0, SuccessCount = 0;

            Shuba.Business.ClusterTarget _ClusterTarget = new Shuba.Business.ClusterTarget();
            List<ClusterTargetInfo> list = _ClusterTarget.GetListApproval(ddlYear.Text, HttpContext.Current.User.Identity.Name, Session["UnitID"].ToString());

            foreach (ClusterTargetInfo item in list)
            {
                try
                {
                    if (Approve(item.ClusterID, true) > 0) SuccessCount++;
                    else ErrorCount++;
                }
                catch (Exception)
                {
                    ErrorCount++;
                }
            }
            if (SuccessCount > 0 || ErrorCount > 0)
            {
                msg = "Approval Notification\\n\\nTotal record to approve : " + list.Count + "Record(s)\\nSuccessfully Approve : " + SuccessCount + " Record(s)\\nFailed to Approve : " + ErrorCount + " Record(s)";
            }
            BindData();
            Alert(msg);
        }

        protected void btnRejectAll_Click(object sender, EventArgs e)
        {
            int ErrorCount = 0, SuccessCount = 0;

            Shuba.Business.ClusterTarget _ClusterTarget = new Shuba.Business.ClusterTarget();
            List<ClusterTargetInfo> list = _ClusterTarget.GetListApproval(ddlYear.Text, HttpContext.Current.User.Identity.Name, Session["UnitID"].ToString());

            foreach (ClusterTargetInfo item in list)
            {
                try
                {
                    if (Approve(item.ClusterID, false) > 0) SuccessCount++;
                    else ErrorCount++;
                }
                catch (Exception)
                {
                    ErrorCount++;
                }
            }
            if (SuccessCount > 0 || ErrorCount > 0)
            {
                msg = "Approval Notification\\n\\nTotal record to reject : " + list.Count + "Record(s)\\nSuccessfully Reject : " + SuccessCount + " Record(s)\\nFailed to Reject : " + ErrorCount + " Record(s)";
            }
            BindData();
            Alert(msg);
        }
    }   
 }

